iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 23
0
Mobile Development

30天手滑用Google Flutter解鎖Hybrid App成就系列 第 23

30天Flutter手滑系列 - 聊天室開發(Chat Room)(3)

  • 分享至 

  • xImage
  •  

前一天30天Flutter手滑系列 - 聊天室開發(Chat Room)(2)在除錯上花了不少時間,今天繼續優化及開發新功能。

添加登入訊息

為了讓成功登入有訊息提醒,我們快加入fluttertoast這個套件。

成功後效果就會如下:
https://upload.cc/i1/2019/09/30/e7min0.gif

然後我們登入成功後可以導回首頁,可以加入以下程式碼

Navigator.push(
          context,
          MaterialPageRoute(
              builder: (context) => MyHomePage(currentUserId: user.uid)));

https://upload.cc/i1/2019/09/30/8oFuQO.gif

到目前為止的程式碼如下

login.dart

class LoginPageState extends State<LoginPage> {
  final GoogleSignIn _googleSignIn = GoogleSignIn();
  final FirebaseAuth _auth = FirebaseAuth.instance;
  SharedPreferences prefs;
  FirebaseUser currentUser;

  Future<FirebaseUser> _handleSignIn() async {
    prefs = await SharedPreferences.getInstance();
    final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
    final GoogleSignInAuthentication googleAuth =
        await googleUser.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleAuth.accessToken,
      idToken: googleAuth.idToken,
    );

    final FirebaseUser user =
        (await _auth.signInWithCredential(credential)).user;
    print("signed in " + user.displayName);

    if (user != null) {
      // 檢查是否登入
      final QuerySnapshot result = await Firestore.instance
          .collection('users')
          .where('id', isEqualTo: user.uid)
          .getDocuments();
      final List<DocumentSnapshot> documents = result.documents;
      if (documents.length == 0) {
        // 如果是新使用者就更新
        Firestore.instance.collection('users').document(user.uid).setData({
          'nickname': user.displayName,
          'photoUrl': user.photoUrl,
          'id': user.uid,
          'createdAt': DateTime.now().millisecondsSinceEpoch.toString(),
          'chattingWith': null
        });

        // 把資料存到本地端
        currentUser = user;
        await prefs.setString('id', currentUser.uid);
        await prefs.setString('nickname', currentUser.displayName);
        await prefs.setString('photoUrl', currentUser.photoUrl);
      } else {
        // 把資料存到本地端
        await prefs.setString('id', documents[0]['id']);
        await prefs.setString('nickname', documents[0]['nickname']);
        await prefs.setString('photoUrl', documents[0]['photoUrl']);
        await prefs.setString('aboutMe', documents[0]['aboutMe']);
      }
      Fluttertoast.showToast(msg: "Sign in success");

       Navigator.push(context, MaterialPageRoute(builder: (context) => MyHomePage(currentUserId: user.uid)));
    } else {
      Fluttertoast.showToast(msg: "Sign in fail");
    }

    return user;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('SIGN IN'),
        ),
        body: Center(
          child: RaisedButton(
              child: Text('SIGN IN WITH GOOGLE'),
              onPressed: () {
                _handleSignIn()
                    .then((FirebaseUser user) => print(user))
                    .catchError((e) => print(e));
              }),
        ));
  }
}


參考資料

https://pub.dev/packages/firebase_auth


上一篇
30天Flutter手滑系列 - 聊天室開發(Chat Room)(2)
下一篇
30天Flutter手滑系列 - 聊天室開發(Chat Room)(4)
系列文
30天手滑用Google Flutter解鎖Hybrid App成就30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言